//
//  OrdertoSureVC.m
//  NewPro
//
//  Created by 何荧红 on 2018/10/8.
//  Copyright © 2018 何荧红. All rights reserved.
//

#import "OrdertoSureVC.h"
#import "AlipayStore.h"
#import <AlipaySDK/AlipaySDK.h>
#import "OrderCenterViewController.h"
#import "WXApi.h"
#import "SetTradingPassWordViewController.h"
#import "InputTradingPassWordView.h"
#import "NewWalletList.h"
#import "NewWalletStore.h"
#import "YEModel.h"

@interface OrdertoSureVC ()
{
    BOOL haveBgView;
}
@property (nonatomic, strong) UITextField *motext;

@property (nonatomic,weak) UIButton *btn;

@property (nonatomic, copy) NSString *yuestr;
@property (nonatomic, strong) UILabel *YueLabel;

@property (nonatomic, strong) UIImageView *yueimg;
@property (nonatomic, strong) UIImageView *alipayimg;
@property (nonatomic, strong) UIImageView *wechatimg;

@property (nonatomic, assign) BOOL isYue;
@property (nonatomic, assign) BOOL isAlipay;
@property (nonatomic, assign) BOOL isWechat;

@property (nonatomic,strong) InputTradingPassWordView *tradingPassWordView;
@property (strong, nonatomic) UIView *bgView;
@property (nonatomic,copy) NSString *secret;
@end

@implementation OrdertoSureVC

- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        [_bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didBgViewClick)]];
    }
    return _bgView;
}

- (void)didBgViewClick{
    
    [self.view endEditing:YES];
}

- (InputTradingPassWordView *)tradingPassWordView{
    
    if (!_tradingPassWordView) {
        
        CGFloat speace = 29;
        CGFloat scale = 0.67;
        CGFloat width = (ScreenWidth - speace * 2);
        CGFloat height = width * scale;
        
        _tradingPassWordView = [[InputTradingPassWordView alloc] initWithFrame:CGRectMake(speace, ScreenHeight, width, height)];
        _tradingPassWordView.wherefrom = @"OrdertoSureVC";
        
        MJWeakSelf
        //关闭按钮点击回调
        [_tradingPassWordView returnCloseBlock:^{
            [UIView animateWithDuration:0.25 animations:^{
                
                self.btn.enabled = YES;
                
                self->haveBgView = NO;
                weakSelf.tradingPassWordView.y = ScreenHeight;
                weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
            } completion:^(BOOL finished) {
                [weakSelf.bgView removeFromSuperview];
            }];
        }];
        
        //确定按钮点击回调
        [_tradingPassWordView returnSureBlock:^(NSString *code, UIButton *sender) {
            
            [weakSelf yuePay:code andBtn:sender];
        }];
        
    }
    return _tradingPassWordView;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    
    self.btn.enabled = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setIsYue:(BOOL)isYue{
    _isYue = isYue;
    if (_isYue) {
        _yueimg.image = [UIImage imageNamed:@"支付选中"];
        _alipayimg.image = [UIImage imageNamed:@"支付未选中"];
        _wechatimg.image = [UIImage imageNamed:@"支付未选中"];
        self.isAlipay = NO;
        self.isWechat = NO;
    }
}
- (void)setIsWechat:(BOOL)isWechat{
    _isWechat = isWechat;
    if (_isWechat) {
        _yueimg.image = [UIImage imageNamed:@"支付未选中"];
        _alipayimg.image = [UIImage imageNamed:@"支付未选中"];
        _wechatimg.image = [UIImage imageNamed:@"支付选中"];
        self.isYue = NO;
        self.isAlipay = NO;
    }
}
- (void)setIsAlipay:(BOOL)isAlipay{
    _isAlipay = isAlipay;
    if (_isAlipay) {
        _yueimg.image = [UIImage imageNamed:@"支付未选中"];
        _alipayimg.image = [UIImage imageNamed:@"支付选中"];
        _wechatimg.image = [UIImage imageNamed:@"支付未选中"];
        self.isYue = NO;
        self.isWechat = NO;
    }
}
- (void)setYuestr:(NSString *)yuestr{
    _yuestr = yuestr;
    if (_yuestr) {
        if (_yuestr.length > 0) {
            self.YueLabel.text = [NSString stringWithFormat:@"（当前可用余额¥%@）",_yuestr];
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getYueData];
    [self initCSS];
    
    //判断有没有设置支付密码
    [self ifHaveSetTradingPassWord];
    
    //注册支付宝通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResultZFB:) name:Notify_ZFB object:nil];
    
    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)getYueData{
    
    [[[AlipayStore alloc]init] GetYuePayWithPrams:@{} Success:^(NSDictionary *res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            
            YEModel *model = [YEModel mj_objectWithKeyValues:res[@"data"][@"items"]];
            
            self.yuestr = [NSString stringWithFormat:@"%.2f",model.dividedTotal + model.returnTotal + model.recommendAmount];
        }else{
            [self showMBPError:res[@"msg"]];
        }
    } Failure:nil];
}
- (void)jifenPay{
    if (![NewWalletList sharedInstance].tradingPassWordSeted) {
        self.btn.enabled = YES;
        SetTradingPassWordViewController *VC = [[SetTradingPassWordViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
        return;
    }
    [self.view insertSubview:self.bgView belowSubview:self.tradingPassWordView];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self->haveBgView = YES;
        self.tradingPassWordView.y = iPhoneX_Top;
        [self.tradingPassWordView setBecomeFirstResponder:YES];
        self.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    }];
}
- (void)yuePay:(NSString *)secret andBtn:(UIButton *)sender{
    MJWeakSelf
    [[[AlipayStore alloc]init] YuePayWithSecret:secret andOrderId:self.OrderID Success:^(NSString *Msg) {
        sender.enabled = YES;
        weakSelf.btn.enabled = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:PUTFORWARDSUCCESS object:nil];
        NSString *status = @"";
        if ([Msg isEqualToString:@"success"]) {
            status = @"alipaySuccess";
        }else{
            status = @"alipayFailure";
            [weakSelf showMBPError:Msg];
        }
        [weakSelf getOrderPayResultZFB:[NSNotification notificationWithName:Notify_ZFB object:status]];
    } Failure:^(NSError *error) {
        sender.enabled = YES;
        weakSelf.btn.enabled = YES;
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

- (void)initCSS{
    
    [self setNavBarWithTitle:@"支付订单"];
    UIView *moneyView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    moneyView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:moneyView];
    UILabel *money = [[UILabel alloc]init];
    money.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:16];
    money.textColor = [UIColor colorWithHexString:@"FF2F2F"];
    money.text = [NSString stringWithFormat:@"¥%@",self.price];
    [moneyView addSubview:money];
    [money mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(moneyView.mas_centerY);
        make.centerX.equalTo(moneyView.mas_centerX);
    }];
    
    UIView *chooseView = [[UIView alloc]initWithFrame:CGRectMake(0, 80, SCREEN_WIDTH, 152)];
    chooseView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:chooseView];
    
    UILabel *yuelab = [[UILabel alloc]init];
    yuelab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:16];
    yuelab.textColor = [UIColor colorWithHexString:@"333333"];
    yuelab.text = @"余额支付";
    [chooseView addSubview:yuelab];
    [yuelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(chooseView.mas_left).offset(14);
        make.top.equalTo(chooseView.mas_top).offset(17);
        make.height.mas_equalTo(16);
    }];
    
    self.YueLabel = [[UILabel alloc]init];
    self.YueLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:12];
    self.YueLabel.textColor = [UIColor colorWithHexString:@"999999"];
    self.YueLabel.text = @"";
    [chooseView addSubview:self.YueLabel];
    [self.YueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(yuelab.mas_right);
        make.centerY.equalTo(yuelab.mas_centerY).offset(3);
    }];
    
    self.yueimg = [[UIImageView alloc]init];
    self.yueimg.image = [UIImage imageNamed:@"支付选中"];
    [chooseView addSubview:self.yueimg];
    [self.yueimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(yuelab.mas_centerY);
        make.right.equalTo(chooseView.mas_right).offset(-14);
        make.width.mas_equalTo(23);
        make.height.mas_equalTo(23);
    }];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"F1F1F1"];
    [chooseView addSubview:line];
    
    UILabel *alipaylab = [[UILabel alloc]init];
    alipaylab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:16];
    alipaylab.textColor = [UIColor colorWithHexString:@"333333"];
    alipaylab.text = @"支付宝支付";
    [chooseView addSubview:alipaylab];
    [alipaylab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(chooseView.mas_left).offset(14);
        make.top.equalTo(line.mas_top).offset(17);
        make.height.mas_equalTo(16);
    }];
    
    self.alipayimg = [[UIImageView alloc]init];
    self.alipayimg.image = [UIImage imageNamed:@"支付未选中"];
    [chooseView addSubview:self.alipayimg];
    [_alipayimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(alipaylab.mas_centerY);
        make.right.equalTo(chooseView.mas_right).offset(-14);
        make.width.mas_equalTo(23);
        make.height.mas_equalTo(23);
    }];
    
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0, 101, SCREEN_WIDTH, 1)];
    line1.backgroundColor = [UIColor colorWithHexString:@"F1F1F1"];
    [chooseView addSubview:line1];
    
    UILabel *wechatlab = [[UILabel alloc]init];
    wechatlab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:16];
    wechatlab.textColor = [UIColor colorWithHexString:@"333333"];
    wechatlab.text = @"微信支付";
    [chooseView addSubview:wechatlab];
    [wechatlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(chooseView.mas_left).offset(14);
        make.top.equalTo(line1.mas_bottom).offset(17);
        make.height.mas_equalTo(16);
    }];
    
    self.wechatimg = [[UIImageView alloc]init];
    self.wechatimg.image = [UIImage imageNamed:@"支付未选中"];
    [chooseView addSubview:self.wechatimg];
    [_wechatimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(wechatlab.mas_centerY);
        make.right.equalTo(chooseView.mas_right).offset(-14);
        make.width.mas_equalTo(23);
        make.height.mas_equalTo(23);
    }];
    UIButton *Yuebutton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    [Yuebutton addTarget:self action:@selector(chooseyue) forControlEvents:UIControlEventTouchUpInside];
    [chooseView addSubview:Yuebutton];
    
    UIButton *Alipay = [[UIButton alloc]initWithFrame:CGRectMake(0, 51, SCREEN_WIDTH, 50)];
    [Alipay addTarget:self action:@selector(chooseAlipay) forControlEvents:UIControlEventTouchUpInside];
    [chooseView addSubview:Alipay];
    
    UIButton *Wechat = [[UIButton alloc]initWithFrame:CGRectMake(0, 102, SCREEN_WIDTH, 50)];
    [Wechat addTarget:self action:@selector(chooseWechat) forControlEvents:UIControlEventTouchUpInside];
    [chooseView addSubview:Wechat];
    
    UIButton *tosure = [[UIButton alloc]initWithFrame:CGRectMake(14, 345, SCREEN_WIDTH - 28, 44)];
    self.btn = tosure;
    tosure.layer.masksToBounds = YES;
    tosure.layer.cornerRadius = 5;
    tosure.backgroundColor = [UIColor colorWithHexString:@"0CA6F0"];
    tosure.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:18];
    [tosure setTitle:@"确认支付" forState:UIControlStateNormal];
    [tosure setTitleColor:[UIColor colorWithHexString:@"FFFFFF"] forState:UIControlStateNormal];
    [tosure addTarget:self action:@selector(tosure:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tosure];
    self.isYue = YES;
    
    [self.view insertSubview:self.tradingPassWordView belowSubview:self.navigationController.navigationBar];
}

- (void)chooseyue{
    self.btn.enabled = YES;
    self.isYue = YES;
}

- (void)chooseAlipay{
    self.btn.enabled = YES;
    self.isAlipay = YES;
}

- (void)chooseWechat{
    self.btn.enabled = YES;
    self.isWechat = YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    self.btn.enabled = YES;
}

- (void)tosure:(UIButton *)btn{
    btn.enabled = NO;
    AlipayStore *store = [[AlipayStore alloc] init];
    MJWeakSelf
    if (self.isYue) {
        if ([self.yuestr floatValue] >= [self.price floatValue]) {
            
            [self jifenPay];
        }else{
            
            self.btn.enabled = YES;
            [self showMBPError:@"您的余额不足"];
        }
    }else if (self.isAlipay) {
        [store alipayWithId:self.OrderID Success:^(NSString *sign){
            [[AlipaySDK defaultService] payOrder:sign fromScheme:@"com.changjie" callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    btn.enabled = YES;
                    NSLog(@"支付成功");
                }else{
                    btn.enabled = YES;
                    NSLog(@"支付失败");
                }
            }];
        } Failure:^(NSError *error) {
            btn.enabled = YES;
            [weakSelf showMBPError:[HttpTool handleError:error]];
        }];
    }else if(self.isWechat){
        [store payWithWeixin:self.OrderID Success:^(NSDictionary *res) {
            //发起微信支付，参数由服务器返回
            PayReq* req = [[PayReq alloc] init];
            req.openID = res[@"appid"];
            req.partnerId = res[@"partnerid"];
            req.prepayId = res[@"prepayid"];
            req.nonceStr = res[@"noncestr"];
            req.timeStamp = [res[@"timestamp"] intValue];
            req.package = res[@"package"];
            req.sign = res[@"sign"];
            [WXApi sendReq:req];
        } Failure:^(NSError *error) {
            btn.enabled = YES;
            [weakSelf showMBPError:[HttpTool handleError:error]];
        }];
    }
}

#pragma mark - 支付宝通知信息
- (void)getOrderPayResultZFB:(NSNotification *)notification{
    
    NSLog(@"tobuy==========发送支付通知");
    
    
    if ([notification.object isEqualToString:@"alipaySuccess"])
    {
        
        [self alert:@"提示" msg:@"支付成功"];
    }
    else
    {
        
        [self alert:@"提示" msg:@"支付失败"];;
    }
}


//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    
    [self.view makeToast:msg duration:2.0 position:CSToastPositionBottom];
    
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0,0,30,30)];
    activityIndicatorView.center = self.view.center;
    activityIndicatorView.y = self.view.centerY + 50;
    [activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];
    
    MJWeakSelf
    //GCD延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        [activityIndicatorView stopAnimating];
        
        OrderCenterViewController *VC = [[OrderCenterViewController alloc] init];
        VC.tag = weakSelf.tag;
        if ([msg isEqualToString:@"支付成功"]) {
            
            VC.index = 1;
            
        }else{
            
            VC.index = 0;
        }
        
        if ([weakSelf.tag isEqualToString:@"订单中心"]) {
            
            if ([msg isEqualToString:@"支付成功"]) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"PaySuccess" object:nil];
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else{
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            
        }else{
            
            [weakSelf.navigationController pushViewController:VC animated:YES];
        }
        
        
    });
    
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 判断有没有设置支付密码
- (void)ifHaveSetTradingPassWord{
    
    MJWeakSelf
    NewWalletStore *store = [[NewWalletStore alloc] init];
    [store getIfHaveSetTradingPassWordSucess:^(BOOL seted) {
        
        [NewWalletList sharedInstance].tradingPassWordSeted = seted;
        
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
}

//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
    if (haveBgView) {
        
        //获取键盘的高度
        NSDictionary *userInfo = [notification userInfo];
        NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [value CGRectValue];
        int height = keyboardRect.size.height;
        self.tradingPassWordView.y = ScreenHeight - height - self.tradingPassWordView.height - iPhoneX_Top - 10;
    }
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    if (haveBgView) {
        
        self.tradingPassWordView.centerY = self.view.centerY - iPhoneX_Top - TAB_BAR_HEIGHT;
    }
}
@end
